package cn.virens.common.project.generator.enums;

import cn.virens.common.mybatis.entity.BaseEnum;
import cn.virens.common.util.core.stream.StreamUtil;
import cn.virens.common.util.exception.APIException;
import org.dromara.hutool.core.reflect.ClassUtil;
import org.dromara.hutool.core.reflect.TypeUtil;
import org.dromara.hutool.core.reflect.method.MethodUtil;
import org.dromara.hutool.core.text.StrUtil;

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.stream.Stream;

public class EnumScan {
    /**
     * 获取枚举KEY对应的类型
     */
    public static Class<?> getKeyType(Class<?> clazz) throws APIException {
        Method method = MethodUtil.getMethodByName(clazz, "getKey");
        if (method == null) return null;

        Type type = TypeUtil.getReturnType(method);
        if (type instanceof Class<?>) {
            return ((Class<?>) type);
        } else {
            return null;
        }
    }

    /**
     * 扫描有效的枚举类
     */
    public static Stream<Class<?>> scanPackage(String... pkgs) {
        return StreamUtil.stream(pkgs)
                .flatMap(p -> ClassUtil.scanPackage(p).stream())
                .filter(BaseEnum.class::isAssignableFrom)
                .sorted(EnumScan::compare);
    }

    /**
     * 排序
     */
    public static int compare(Class<?> a, Class<?> b) throws APIException {
        String s1 = StrUtil.toUnderlineCase(a.getSimpleName());
        String s2 = StrUtil.toUnderlineCase(b.getSimpleName());

        return StrUtil.compare(s1, s2, true);
    }
}
